package com.blb.marry.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blb.marry.entity.Shoppingcart;
import com.blb.marry.entity.User;
import com.blb.marry.service.ShopCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

/**
 * @author lvtian
 * @date 2023/1/30 10:07
 */
@Controller
public class ShopCartController {

    @Controller
    public class OrderController {

        @Autowired
        private ShopCartService shoppingcartService;

        private Random rd = new Random();

        //加入购物车
        @ResponseBody
        @PostMapping("/addCart")
        public String addCart(@RequestBody Shoppingcart cart, HttpServletRequest request, Model model){
            System.out.println(cart);
            User user = (User) request.getSession().getAttribute("user");
            if (user == null){
                return "9";
            }
            DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime now = LocalDateTime.now();
            //id
            String id = now.format(dtf1);
            for (int i = 0; i < 3; i++) {
                id += rd.nextInt(10);
            }
            cart.setShoppingcartId(id);
            cart.setShoppingcartTime(now.format(dtf2));
            cart.setTbUserUserTel(user.getUserTel());
            shoppingcartService.save(cart);
            return "1";
        }

        //显示购物车
        @RequestMapping("/showCart")
        public String showCart(HttpServletRequest request,Model model){
            User user = (User) request.getSession().getAttribute("user");
            List<Shoppingcart> carts = shoppingcartService.list(new QueryWrapper<Shoppingcart>().lambda()
                    .eq(Shoppingcart::getTbUserUserTel, user.getUserTel())
            );
            model.addAttribute("carts",carts);
            return "Shopping_Cart";
        }



    }
}
